<template>
  <div class="spl-container import-container" v-loading="mainLoading"
       :element-loading-text="active=='0'?'文件上传中...':'数据保存中...'"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(244, 248, 248, 0.5)">
    <breadcrumb :data="pathData"></breadcrumb>
    <div class="emp-container">
      <div class="page-title">
        <span>批量导入</span>
      </div>

      <div class="mt-10 spl-step">
        <el-steps :active="active" align-center finish-status="success">
          <el-step title="下载模板/上传文件" description="可下载自定义模板，完善后上传"></el-step>
          <el-step title="文件校验" description="上传文件后，可在线编辑调整"></el-step>
          <el-step title="导入成功"></el-step>
        </el-steps>
      </div>
      <!--第一步-->
      <div v-if="active==0">
        <div class="clearfix emp-upload mt-30 ml-20">
          <el-input class="fl" :readonly="true" v-model="fileName" style="width: 280px;"></el-input>
          <el-upload
            class="fl"
            ref="upload"
            action="/api/sys/no-limit/upload/single"
            :headers="this.$global.setHeaders"
            :file-list="fileList"
            :on-change="fileChange"
            :on-success="uploadSuccess"
            :show-file-list="false"
            :auto-upload="false" :multiple="false">
            <el-button slot="trigger" plain class="ml-10 s-btn">选择文件</el-button>
            <el-button style="margin-left: 10px;" size="small s-btn" type="primary" icon="icon ic-import"
                       @click="submitUpload">
              导入
            </el-button>
          </el-upload>

          <div class="search-row-btn">
            <el-button type="primary" class="s-btn" icon="el-icon-download" @click="exportTemplate">模板下载</el-button>
            <router-link to="/employeeList">
              <el-button type="primary" class="opt-btn yellow-btn s-btn" icon="icon el-icon-close">取消</el-button>
            </router-link>
          </div>
        </div>

        <p class="mt-30"><span class="tip"><i class="el-icon-warning ic-tip-yellow"></i><span>以下导入说明通用</span></span></p>
        <div class="mt-30 import-template">
          <img src="../../assets/images/import-template.png" alt="" width="100%" height="100%">
        </div>
      </div>
      <!--第二步-->
      <div v-show="active==1">
        <div class="error-msg mt-10">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <p class="text-blue" style="width: 100%;"><span class="tip"><i
                  class="el-icon-warning ic-tip-yellow"></i><span>结果：通过校验<span v-text="successCount"></span>条 失败<span
                  v-text="failedCount"></span>条</span></span><span class="open-detail">展开详情</span>
                </p>
              </template>
              <div v-text="'有'+failedCount+'条数据存在逻辑错误或系统数据重复错误'"></div>
              <div v-for="(item,index) in failedData" v-text="'证照号码为：'+item.certificateNumber+', 校验不合法, 跳过此行'"></div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <div class="notes">
          <p>注：所有数据均可导出和删除，每次导入均会校验系统已有数据，正确数据确认导入后可直接导入。</p>
          <p>若想一次性导入全部数据，可点击“取消”终止本次导入，待失败数据修改正确后再全部重新导入</p>
        </div>
        <div class="clearfix">
          <div class="mt-10">
            <span class="mr-10">只看失败</span>
            <el-switch v-model="switchValue" :activeColor="$global.switchColor[0]" active-value="1" inactive-value="0"
                       :inactiveColor="$global.switchColor[1]" @change="changeStatus">
            </el-switch>
          </div>

          <dTable @fetch="getTableData" ref="importTable" :tableHeight="tableHeight" :showSelection="true"
                  :showIndex="true">
            <el-table-column prop="failedReason" label="错误信息" header-align="center" align="left" min-width="300">
              <template slot-scope="scope">
                <p class="text-red" v-text="scope.row.failedReason"></p>
              </template>
            </el-table-column>
            <el-table-column v-for="(item , index) in tableCols" :key="index"
                             :prop="item.formKey" :label="item.formName" header-align="center"
                             :align="item.formTypeCode|parseAlign" width="220">
              <template slot-scope="scope">
                <p>{{scope.row | parseCellValue(item, $global)}}</p>
              </template>
            </el-table-column>
            <template slot="pagination-btns" slot-scope="scope">
              <el-button type="primary" icon="ic-export" class="s-btn" @click="exportData(switchValue)">导出</el-button>
              <el-button type="primary" class="opt-btn yellow-btn s-btn" icon="icon el-icon-delete" @click="delData">
                删除
              </el-button>
            </template>
          </dTable>
        </div>

        <div class="operate-btns-bottom">
          <el-button class="cancel-btn-border" @click="active=0">取消</el-button>
          <el-button type="primary" class="ml-30" @click="saveData">确认导入</el-button>
        </div>
      </div>
      <!--第三步-->
      <div v-show="active==2">
        <div class="success-msg">
          <i class="el-icon-success"></i>
          <p class="msg-title">导入完成</p>
          <p class="msg-detail" v-text="'您已成功导入'+successCount+'条数据'"></p>
          <p class="msg-detail"><span v-text="failedCount +'条数据导入忽略，存在逻辑错误或系统数据重复错误'"></span><a class="text-blue a-aim"
                                                                                                href="#"
                                                                                                @click="exportData('1')">（点击下载）</a>
          </p>
          <router-link to="/employeeList">
            <el-button type="primary" class="mt-30">返回员工列表</el-button>
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import dTable from '../../components/common/table'
  export default {
    components: {dTable},
    data () {
      return {
        mainLoading: false,
        // 导航
        pathData: [
          {name: '员工信息'},
          {name: '员工列表', path: '/employeeList'}
        ],
        switchValue: '1',
        fileName: "",
        fileList: [],
        active: 0,
        tableData: [],
        moduleCode: '',
        subModuleCode: '',
        moduleList: {
          employee_info: '个人基本信息导入模板',
          edu_info: '教育经历导入模板',
          worked_info: '工作经历导入模板',
          work_info: '在职信息导入模板',
          account_infobank_info: '账户信息-银行卡信息导入模板',
          account_infowelfare_info: '账户信息-福利信息导入模板',
          contact_info: '合同信息导入模板',
          attach_infoattachment_info: '资料信息-附件资料导入模板',
          attach_infolicense_info: '资料信息-员工证照导入模板'
        },
        tableCols: [],
        fileId: '',
        failedCount: 0,
        successCount: 0,
        failedData: []
      }
    },
    created () {
      this.moduleCode = this.$route.query.moduleCode
      this.subModuleCode = this.$route.query.subModuleCode
      this.$nextTick(() => {
        this.getTableCols()
      })
    },
    filters: {
      parseAlign (value){
        if (value === '3' || value === '4' || value === '5') {
          return 'center'
        }
        return 'left'
      },
      parseCellValue (value, item, $global){
        var cellValue = value[item.formKey]
        if (cellValue == undefined || cellValue == null || cellValue == '') {
          return cellValue
        }
        if (item.formTypeCode === '3') {
          return $global.dateToStrByFormart(cellValue, 'yyyy-MM-dd')
        } else if (item.formTypeCode === '4') {
          return $global.dateToStrByFormart(cellValue, 'mm:ss')
        } else if (item.formTypeCode === '5') {
          return $global.dateToStrByFormart(cellValue, 'yyyy-MM-dd HH:mm:ss')
        }
        return value[item.formKey]
      }
    },
    computed: {
      tableHeight: function () {
        return this.$global.bodyHeight - 470 + 'px'
      }
    },
    watch: {},
    methods: {
      getTableCols (){
        this.$http({
          url: '/employeeInfo/getEmpTableFields',
          method: 'get',
          params: {
            moduleCode: this.moduleCode,
            subModuleCode: this.subModuleCode
          }
        }).then(({data}) => {
          this.tableCols = data
        }).catch((data) => {
          this.$message({
            message: '系统异常',
            type: 'error'
          })
        })
      },
      submitUpload () {
        if(this.fileName !=''){
          this.mainLoading = true
          this.fileName = ''
          this.$refs.upload.submit()
        }else{
          this.$message({
            message: '请选择文件',
            type: 'warning'
          })
        }
      },
      //上传成功后
      uploadSuccess (response, file, fileList){
        file.name = ''
        var fileId = response.data.id//文件id
        this.fileId = fileId
        this.$http({
          url: '/employeeInfo/parseExcel',
          method: 'get',
          params: {
            fileId: fileId,
            moduleCode: this.moduleCode,
            subModuleCode: this.subModuleCode
          }
        }).then(({data}) => {
          //跳转到下一步查询列表数据
          this.getTableData()
          //获取导入统计信息0
          this.getImportCountInfo()
          this.getFailedData()
          this.mainLoading = false
          this.$refs.upload.clearFiles()
          this.active = 1
        })
      },
      getTableData(){
        var params = [{property: "fileId", value: this.fileId},
          {property: "status", value: parseInt(this.switchValue)},
          {property: "moduleCode", value: this.moduleCode},
          {property: "subModuleCode", value: this.subModuleCode},
        ]
        this.$refs.importTable.fetch(params, 'post', '/employeeInfo/listEmployeeInfoImportPages')
      },
      getFailedData(){
        this.$http({
          url: '/employeeInfo/listEmployeeInfoImportPages',
          method: 'post',
          data: {
            query: [{property: "fileId", value: this.fileId},
              {property: "status", value: 1},
              {property: "moduleCode", value: this.moduleCode},
              {property: "subModuleCode", value: this.subModuleCode},
            ],
            page: 1,
            size: 1000000
          }
        }).then(({data}) => {
          this.failedData = data.rows
        })
      },
      changeStatus(value){
        this.switchValue = value;
        this.getTableData()
      },
      getImportCountInfo(){
        this.$http({
          url: '/employeeInfo/selectImportCount',
          method: 'post',
          data: this.$qs.stringify({
            fileId: this.fileId, moduleCode: this.moduleCode,
            subModuleCode: this.subModuleCode
          })
        }).then(({data}) => {
          if (data.code == 0) {
            this.failedCount = data.data.failedCount
            this.successCount = data.data.successCount
          } else {
            this.$message({
              message: '系统异常',
              type: 'error'
            })
          }
        }).catch((data) => {
          this.$message({
            message: '系统异常',
            type: 'error'
          })
        })
      },
      saveData(){
        this.mainLoading = true
        this.$http({
          url: '/employeeInfo/importSave',
          method: 'post',
          data: this.$qs.stringify({
            fileId: this.fileId, moduleCode: this.moduleCode,
            subModuleCode: this.subModuleCode
          })
        }).then(({data}) => {
          if (data.code == 0) {
            this.active = 2
          } else {
            this.$message({
              message: '系统异常',
              type: 'error'
            })
          }
          this.mainLoading = false
        })
      },
      fileChange (file, fileList) {
        this.fileName = file.name
      },
      //  导出模板
      exportTemplate () {
        this.$downloadFile('/employeeInfo/getExportTemplate', 'get', {
          moduleCode: this.moduleCode,
          subModuleCode: this.subModuleCode
        }, this.$global.EXCEL, this.moduleList[this.moduleCode + this.subModuleCode]);
      },
      //导出
      exportData(switchValue){
        this.$downloadFile('/employeeInfo/mongoExport', 'post', {
          fileId: this.fileId,
          moduleCode: this.moduleCode,
          subModuleCode: this.subModuleCode,
          status: parseInt(switchValue)
        }, this.$global.EXCEL);
      },
      delData(){
        var selections = this.$refs.importTable.selections;
        if (selections.length == 0) {
          this.$message({
            message: '请选择需要删除的数据',
            type: 'warning'
          })
          return
        }
        var ids = []
        selections.forEach(item => {
          ids.push(item.id)
        })
        this.$http({
          url: '/employeeInfo/remove',
          method: 'post',
          data: this.$qs.stringify({
            ids: ids.join(","),
            moduleCode: this.moduleCode,
            subModuleCode: this.subModuleCode
          })
        }).then(({data}) => {
          this.getTableData()
          this.getImportCountInfo()
          this.getFailedData()
        })
      }
    }
  }
</script>
<style lang="less" scoped>
  .emp-container {
    padding: 20px 30px;
  }

  .import-container {
    position: relative;
    height: 100%;
  }

  .import-template {
    text-align: center;
    img {
      display: inline-block;
      width: 90%;
      max-width: 1393px;
      height: 309px;
    }
  }

  .error-msg {
    background-color: #EFF2F7;
    padding: 10px 20px;
  }

  .notes {
    padding: 10px 20px;
  }
</style>
